#include "performinstallation.h"
#include "ui_performinstallation.h"
#include "installthread.h"
#include "installationcomplete.h"

PerformInstallation::PerformInstallation(QString installPath, QPoint point, QWidget *parent) :
    QWidget(parent),
    ui(new Ui::PerformInstallation),
    installPath(installPath),
    filesSize(0),
    msgBox(nullptr)
{
    ui->setupUi(this);
    this->move(point);
    this->setWindowIcon(QIcon(":/resourceFile/xin.ico"));
    this->setWindowTitle(tr("%1 %2 安装").arg(xin::exeName).arg(xin::versions));
    ui->labelIco->setPixmap(QPixmap(":/resourceFile/xin.ico"));
    ui->labelIco->setScaledContents(true); //自适应
    ui->labelSelectInstall->setText(tr("正在安装"));
    ui->labelSelectDir->setText(QString("\"%1 %2 \" %3").arg(xin::exeName).arg(xin::versions).arg(tr("正在安装,请稍候...")));

    ui->textEdit->setReadOnly(true);
    ui->textEdit->setCursor(QCursor(Qt::CursorShape::ArrowCursor));

    ui->pushButtonCancel->setText(tr("取消(C)"));
    ui->pushButtonCancel->setShortcut(Qt::Key_C);
    ui->pushButtonNext->setText(tr("下一步(N) >"));
    ui->pushButtonCancel->setShortcut(Qt::Key_N);
    ui->pushButtonLastStep->setText(tr("< 上一步(B)"));
    ui->pushButtonCancel->setShortcut(Qt::Key_B);
    connect(ui->pushButtonNext, SIGNAL(clicked(bool)), this, SLOT(pushButtonNext()));
    connect(ui->pushButtonCancel, SIGNAL(clicked(bool)), this, SLOT(buttonCancel()));
    connect(ui->pushButtonLastStep, SIGNAL(clicked(bool)), this, SLOT(buttonLastStep()));
    ui->pushButtonCancel->setEnabled(false);
    ui->pushButtonNext->setEnabled(false);
    ui->pushButtonLastStep->setEnabled(false);

    files = getFiles(xin::qrcName);

    initData();
}

PerformInstallation::~PerformInstallation()
{
    delete ui;
}

void PerformInstallation::closeEvent(QCloseEvent *event)
{
    QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                       tr("你确定要退出%1 %2 的安装吗?").arg(xin::exeName).arg(xin::versions),
                                       QMessageBox::Yes | QMessageBox::No);

    box->button(QMessageBox::Yes)->setText(tr("是"));
    box->button(QMessageBox::No)->setText(tr("否"));
    box->button(QMessageBox::No)->setFocus(); //设置焦点
    //此move会有变动
    box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
    int ret = box->exec();
    if (ret != QMessageBox::Yes) {
        event->ignore();
    }
}

void PerformInstallation::errorData(QString error)
{
    ui->pushButtonLastStep->setEnabled(true);
    if (msgBox == nullptr) {
        msgBox = new QMessageBox(this);
        msgBox->setText(error);
        msgBox->exec();
    }
    isInstallSucceed(false);
}

void PerformInstallation::updateData(double data)
{
    ui->progressBar->setValue(data);
    if (!files.isEmpty()) {
        ui->labelProgress->setText(tr("抽取: ") +
                                   QFileInfo(files.last()).fileName() + "..."
                                   + QString("%1%").arg((int)data));
        ui->textEdit->append(tr("抽取: ") + QFileInfo(files.last()).fileName() + "...");
        emit signalStartCopy(files.last()); //返给线程
        files.removeLast();
    }
    else {
        isInstallSucceed(true);
    }
}

void PerformInstallation::pushButtonNext()
{

}

void PerformInstallation::buttonCancel()
{
    QMessageBox* box = new QMessageBox(QMessageBox::Question, tr("%1 %2的安装").arg(xin::exeName).arg(xin::versions) ,
                                       tr("你确定要退出%1 %2 的安装吗?").arg(xin::exeName).arg(xin::versions),
                                       QMessageBox::Yes | QMessageBox::No);

    box->button(QMessageBox::Yes)->setText(tr("是"));
    box->button(QMessageBox::No)->setText(tr("否"));
    box->button(QMessageBox::No)->setFocus(); //设置焦点
    //此move会有变动
    box->move(this->x() + (((this->width() - 310) / 2)), this->y() + ((this->height() - 120) / 2));
    int ret = box->exec();
    if (ret == QMessageBox::Yes) {
        exit(1);
    }
}

void PerformInstallation::buttonLastStep()
{
    emit signalShowTargetDirectory();
    this->hide();
}

QStringList PerformInstallation::getFiles(QString path)
{
    if (!path.endsWith('/')) {
        path.append('/');
    }
    QDir dir(path);
    QStringList files;

    foreach (QString name, dir.entryList(QDir::AllEntries | QDir::NoDotAndDotDot)) {
        QString newPath = path + name;
        if (!QFileInfo(newPath).isSymLink() && QFileInfo(newPath).isDir()) {
            files.append(getFiles(newPath));
        }
        qDebug() << QFileInfo(newPath).size();
        files.append(newPath);
    }

    return files;
}

void PerformInstallation::setRegedit()
{
#if defined (Q_OS_WINDOWS)

    //设置注册表
    //以下注册表是为了让web端可以启动自己的程序
    QSettings settingsXiaoXin("HKEY_CLASSES_ROOT\\" + xin::exeName + "\\", QSettings::NativeFormat);
    QSettings settingsDefaulticon("HKEY_CLASSES_ROOT\\" + xin::exeName + "\\Defaulticon", QSettings::NativeFormat);
    QSettings settingsCommand("HKEY_CLASSES_ROOT\\" + xin::exeName + "\\shell\\open\\command", QSettings::NativeFormat);
    QSettings settingsVersions("HKEY_CLASSES_ROOT\\" + xin::exeName +  "Versions", QSettings::NativeFormat);

    settingsXiaoXin.setValue("URL Protocol", installPath + xin::exeName + ".exe");
    settingsDefaulticon.setValue(".", installPath + xin::exeName + ".exe");
    settingsCommand.setValue(".", installPath + xin::exeName + ".exe");
    settingsVersions.setValue("Versions", xin::versions);


    //以下写入Win系统卸载列表
    //HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall 此路径为卸载列表
    QSettings settingsUninstall("HKEY_LOCAL_MACHINE\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\" + xin::exeName,
                                QSettings::NativeFormat);
    settingsUninstall.setValue("DisplayName", xin::exeName); // 程序名字
    settingsUninstall.setValue("UninstallString", installPath + xin::UninstallName); //卸载路径
    settingsUninstall.setValue("InstallLocation", installPath); // 安装目录
    settingsUninstall.setValue("DisplayIcon", installPath + xin::iconName); //显示在你的应用程序名称旁边的图标的路径，文件名和索引
    settingsUninstall.setValue("Publisher", ""); // 发布者(或公司)的名称
    settingsUninstall.setValue("ModifyPath", ""); // 应用程序的修复程序的路径和文件名
    settingsUninstall.setValue("InstallSource", installPath); // 应用程序的安装路径
    settingsUninstall.setValue("ProductID", ""); // 应用程序的产品 ID
    settingsUninstall.setValue("RegOwner", ""); // 应用程序的注册拥有者
    settingsUninstall.setValue("RegCompany", ""); // 应用程序的注册公司
    settingsUninstall.setValue("HelpLink", ""); // 技术支持的网站链接
    settingsUninstall.setValue("HelpTelephone", ""); // 技术支持电话
    settingsUninstall.setValue("URLUpdateInfo", ""); // 应用程序的在线更新网址链接
    settingsUninstall.setValue("URLInfoAbout", "");  // 应用程序的主页链接
    settingsUninstall.setValue("DisplayVersion", xin::versions); // 应用程序的显示版本
    settingsUninstall.setValue("VersionMajor", 0); // 应用程序的主版本号
    settingsUninstall.setValue("VersionMinor", 0); // 应用程序的副版本号
    settingsUninstall.setValue("NoModify", 0); // 如果卸载程序没有修改应用程序的选项
    settingsUninstall.setValue("NoRepair", 0); // 如果卸载程序没有修复安装程序的选项
#else
    QSettings settingsVersions(xin::exeName + "Versions", xin::exeName);

    settingsVersions.setValue("Versions", xin::versions);
#endif
}

void PerformInstallation::initData()
{
#if defined(Q_OS_LINUX)
    installPath.replace("\\", "/");
    qDebug() << installPath;
    if (QDir(installPath).mkpath("QwqZxbvgfjhAcxbgdhsaXBDgqwZCBasefadf")) {
        qDebug() << installPath + "QwqZxbvgfjhAcxbgdhsaXBDgqwZCBasefadf";
        QDir(installPath + "QwqZxbvgfjhAcxbgdhsaXBDgqwZCBasefadf").removeRecursively();
        ui->textEdit->append(tr("输出目录: ") + installPath);
        InstallThread* installThread = new InstallThread(installPath, files.size());
        QThread* thread = new QThread();
        installThread->moveToThread(thread);
        connect(this, SIGNAL(signalStartCopy(QString)), installThread, SLOT(startCopy(QString)));
        connect(installThread, SIGNAL(signalData(double)), this, SLOT(updateData(double)));
        thread->start();
        if (!files.isEmpty()) {
            emit signalStartCopy(files.last());
            files.removeLast();
        }
    }

#else
    ui->textEdit->append(tr("输出目录: ") + installPath);
    InstallThread* installThread = new InstallThread(installPath, files.size());
    QThread* thread = new QThread();
    installThread->moveToThread(thread);
    connect(this, SIGNAL(signalStartCopy(QString)), installThread, SLOT(startCopy(QString)));
    connect(installThread, SIGNAL(signalData(double)), this, SLOT(updateData(double)));
    connect(installThread, SIGNAL(signalErrorData(QString)), this, SLOT(errorData(QString)));
    thread->start();
    if (!files.isEmpty()) {
        emit signalStartCopy(files.last());
        files.removeLast();
    }
#endif
}

void PerformInstallation::isInstallSucceed(bool isSucceed)
{
    if (isSucceed) {
        setRegedit(); //写注册表
        ui->labelProgress->setText(tr("已完成%1 %2的安装").arg(xin::exeName).arg(xin::versions));
        ui->textEdit->append(tr("完成"));
        ui->progressBar->setValue(100);
        InstallationComplete* installationComplete = new InstallationComplete(installPath, isSucceed);
        installationComplete->show();
        this->hide();
    }
    else {
        ui->labelProgress->setText(tr("%1 %2 的安装已失败").arg(xin::exeName).arg(xin::versions));
        ui->textEdit->append(tr("安装失败"));
        InstallationComplete* installationComplete = new InstallationComplete(installPath, isSucceed);
        QDesktopWidget* desktop = QApplication::desktop(); // =qApp->desktop();也可以
        installationComplete->move((desktop->width() - installationComplete->width())/2, (desktop->height() - installationComplete->height())/2);
        installationComplete->show();
        this->hide();
    }
}
